﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using Window;
using System.Runtime.InteropServices;
using System.Text;

namespace Voize
{
    internal partial class fPlayer : Form
    {

        #region Constructors
        internal fPlayer()
        {
            InitializeComponent();
            
            CRandom random = new CRandom();
            CPlayPosition PlayPosition = new CPlayPosition(ref PlayBar);
            CNotify notification = new CNotify(SysTrayIcon);
            m_Height = this.Height;
            
            m_Pl = new CPlaylist(ref this.dPlaylist,random);
            m_Settings = new CSettings();
            m_Player = new CPlayer(ref m_Pl, PlayPosition, notification, m_WebStream,m_Settings);
            
            CStartupHandler handler = new CStartupHandler(m_Settings);
            m_Handler = handler;

            this.tFileDisplay.Text = "Welcome to Voize";
            this.label1.Text = "00:00";
            this.label2.Text = " [00:00]";

            this.SysTrayIcon.ContextMenu = this.SysTrayMenu;

            CPlaylistStatus.PlaylistChanged = false;
          
            m_Tip = new ToolTip();

            m_ScrollingDisplay = new CScrollingDisplay(ref tFileDisplay);

            this.CreateCacheFile();
            m_Volume = new CVolume(this.VolumeControl,m_WebStream);

            m_Position = PlayPosition;
            m_Notifier = notification;

            this.CustomScrollbar.Minimum = 0;

            this.DoubleBuffered = true;
        }


        internal fPlayer(string playlist,string root)
        {
            InitializeComponent();

            CRandom random = new CRandom();
            CPlayPosition PlayPosition = new CPlayPosition(ref PlayBar);
            CNotify notification = new CNotify(SysTrayIcon);
            m_Height = this.Height;

            m_Pl = new CPlaylist(ref this.dPlaylist,random);
            m_Settings = new CSettings();
            m_Player = new CPlayer(ref m_Pl, PlayPosition, notification, m_WebStream,m_Settings);

            CStartupHandler handler = new CStartupHandler(m_Settings);
            m_Handler = handler;

            this.tFileDisplay.Text = "Welcome to Voize";
            this.label1.Text = "00:00";
            this.label2.Text = " [00:00]";
            this.SysTrayIcon.ContextMenu = this.SysTrayMenu;

            CPlaylistStatus.PlaylistChanged = false;

            m_Pl.Load(playlist, root);
            m_SkipLastSessionPlaylist = true;
           

            m_Tip = new ToolTip();

            m_ScrollingDisplay = new CScrollingDisplay(ref tFileDisplay);

            this.CreateCacheFile();
            m_Volume = new CVolume(this.VolumeControl,m_WebStream);

            m_Position = PlayPosition;
            m_Notifier = notification;

            this.CustomScrollbar.Minimum = 0;

            this.DoubleBuffered = true;
        }


        internal fPlayer(string file)
        {

            InitializeComponent();

            m_SkipLastSessionPlaylist = false;

            CRandom random = new CRandom();
            CPlayPosition PlayPosition = new CPlayPosition(ref PlayBar);
            CNotify notification = new CNotify(SysTrayIcon);
            m_Height = this.Height;

            m_Pl = new CPlaylist(ref this.dPlaylist, random);
            m_Settings = new CSettings();
            m_Player = new CPlayer(ref m_Pl, PlayPosition, notification, m_WebStream, m_Settings);

            CStartupHandler handler = new CStartupHandler(m_Settings);
            m_Handler = handler;

            this.tFileDisplay.Text = "Welcome to Voize";
            this.label1.Text = "00:00";
            this.label2.Text = " [00:00]";

            this.SysTrayIcon.ContextMenu = this.SysTrayMenu;

            CPlaylistStatus.PlaylistChanged = false;

            m_Tip = new ToolTip();

            m_ScrollingDisplay = new CScrollingDisplay(ref tFileDisplay);

            this.CreateCacheFile();

            m_FileFromArgs = file;
            m_FileFromLoad = true;

            m_Volume = new CVolume(this.VolumeControl,m_WebStream);

            m_Position = PlayPosition;
            m_Notifier = notification;

            this.CustomScrollbar.Minimum = 0;

            this.DoubleBuffered = true;
        }
        #endregion

        #region Privates
        private int m_Height;
        private CPlayer m_Player;
        private CPlaylist m_Pl;
        private CSettings m_Settings;
        private CStartupHandler m_Handler;
        private bool m_SkipLastSessionPlaylist;
        private ToolTip m_Tip;
        private CScrollingDisplay m_ScrollingDisplay;
		CInternetStream m_WebStream = new CInternetStream();
        private string m_FileFromArgs;
        private bool m_FileFromLoad;
        private int m_List_Height;
        private DataGridViewCellMouseEventArgs m_Ev;
        private int m_LastPopupIndex;
        private Color m_LastPopupColor;
        private CVolume m_Volume;
        private bool m_IsMixerShown = false;
        private fMixer m_Mixer;
        private int m_LastSelectedRow;
        private CNotify m_Notifier;
        private CPlayPosition m_Position;
        private CServer m_Server;
        #endregion

        #region Private methods
        private void AddFileFromArgument()
        {
            m_Pl.AddSingleFile(m_FileFromArgs);
            CPlayerStatus.PlayListLoaded = false;
            dPlaylist[0, dPlaylist.RowCount - 2].Selected = true;
        }


        private void CreateCacheFile()
        {
            string CachePath;

            CachePath = Environment.GetEnvironmentVariable("APPDATA");
            CachePath += @"\Scrobbler\";

            if (!Directory.Exists(CachePath))
                Directory.CreateDirectory(CachePath);

            CachePath = CachePath + "Cache";

            if (!File.Exists(CachePath))
            {
                File.Create(CachePath);
            }
        }



        private void AssociateVoizeWithExplorer()
        {
            m_Settings.MakeFileAssociation("voize");
        }



        private void UpdateDisplay()
        {      
            while (m_Player.IsFinished == false)
            {
                this.label1.Text = m_Player.GetCurrentPlayingPosition;
            }
        }


        private void StartStopScrolling()
        {
            if (tFileDisplay.Text != "")
            {
                if (m_ScrollingDisplay.IsScrolling)
                    m_ScrollingDisplay.StopScrolling();
                else
                    m_ScrollingDisplay.StartScrolling();
            }
        }



        private void ShowSearch()
        {
            this.Cursor = Cursors.WaitCursor;
            fSearch SearchDialog = new fSearch(m_Pl.SoundCollection, m_Player, this.dPlaylist);
            SearchDialog.ShowDialog();
            this.Cursor = Cursors.Default;
        }



        private void NextSong()
        {
            CPlayerStatus.PlayListLoaded = false;
            m_Pl.NextSong();
            bPause.Image =
                    Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");

            this.HighlightPlayingSong();
        }



        private void SetRandom()
        {
            if (m_Pl.IsRandom == false)
            {
                m_Pl.IsRandom = true;
                this.lMode.Text = "RND";
            }
            else
            {
                m_Pl.IsRandom = false;
                this.lMode.Text = "";
            }

        }



        private void HighlightPlayingSong()
        {
            for (int i = 0; i < dPlaylist.RowCount - 1; i++)
            {
                if (dPlaylist[0, i].RowIndex != m_LastSelectedRow)
                    dPlaylist[0, i].Style.ForeColor = Color.RoyalBlue;
                else
                    dPlaylist[0, i].Style.ForeColor = Color.White;
            }
        }



        private void PreviousSong()
        {
            CPlayerStatus.PlayListLoaded = false;
            m_Pl.PreviousSong();
            bPause.Image =
                    Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");

            this.HighlightPlayingSong();
        }


        private void SavePlaylist()
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Title = "Save playlist...";
            sd.Filter = CMediaSupport.PlaylistExtensions;
			sd.AutoUpgradeEnabled = false;

            if (sd.ShowDialog() == DialogResult.OK)
                m_Pl.Save(sd.FileName);
        }


        private void Import()
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.ShowNewFolderButton = false;
			

            if (fd.ShowDialog() == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                m_Pl.FromFolder(fd.SelectedPath);
                this.Cursor = Cursors.Default;
                CPlaylistStatus.PlaylistChanged = true;
                CPlayerStatus.PlayListLoaded = false;
            }

        }


        private void Open()
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Filter = CMediaSupport.Extensions;
			od.AutoUpgradeEnabled = false;

            if (od.ShowDialog() == DialogResult.OK)
            {
                CPlayerStatus.PlayListLoaded = true;

                if (od.FileName.EndsWith(".m3u") || od.FileName.EndsWith(".voize"))
                {
                    m_Player.Stop();
                    this.tFileDisplay.Text = "";
                    this.label1.Text = "";

                    this.Cursor = Cursors.WaitCursor;
                    string root;
                    root = Path.GetDirectoryName(od.FileName);
                    root += @"\";
                    m_Pl.Load(od.FileName, root);
                    this.Cursor = Cursors.Default;
                    CPlaylistStatus.PlaylistChanged = false;

                    m_Player.ClearPlayPositionIndicatorValue();
                }
                else
                {
                    m_Pl.AddSingleFile(od.FileName);
                    CPlaylistStatus.PlaylistChanged = true;
                    CPlayerStatus.PlayListLoaded = false;
                }
            }
        }


        private void ClearList()
        {
            fMessagebox box =
                new fMessagebox("Are you sure?", "All songs will be removed from the playlist.");
            if (box.ShowDialog() == DialogResult.OK)
            {
                CPlayerStatus.PlayListLoaded = true;
                m_Player.Stop();
                this.tFileDisplay.Text = "";
                this.label1.Text = "";
                this.label2.Text = "";
                m_Pl.Clear();
                m_Player.ClearPlayPositionIndicatorValue();
            }

        }


        private void PlayPause()
        {

            if (this.dPlaylist.RowCount - 1 != 0)
            {

                if (m_Player.IsPaused)
                {
                    string val = (string)dPlaylist[0, m_LastSelectedRow].Value;
                    if (val.StartsWith("http://"))
                    {
                        m_Player.Pause(false);
                        m_WebStream.Play(val, m_Volume);
                        bPause.Image =
                            Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
                        m_ScrollingDisplay.StartScrolling();
                    }
                    else
                    {
                        m_Player.Pause(false);
                        bPause.Image =
                            Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
                        m_ScrollingDisplay.StartScrolling();
                    }
                }
                else
                {
                    if (dPlaylist[0, m_LastSelectedRow].Value != null)
                    {
                        string val = (string)dPlaylist[0, m_LastSelectedRow].Value;

                        if (val.StartsWith("http://"))
                        {
                            m_Player.Pause(true);
                            m_WebStream.Stop();
                            bPause.Image =
                                Image.FromFile(Application.StartupPath + @"\Icons\player_pause_green.png");
                            m_ScrollingDisplay.StopScrolling();
                        }
                        else
                        {
                            m_Player.Pause(true);
                            bPause.Image =
                                Image.FromFile(Application.StartupPath + @"\Icons\player_pause_green.png");
                            m_ScrollingDisplay.StopScrolling();
                        }
                    }
                }
            }

        }


        private void RemoveSongFromPlaylist(DataGridViewCellMouseEventArgs e)
        {
            int OriginalRowIndex = e.RowIndex;

            if (!m_Player.IsPlayingSong(m_Pl.GetSong(e.RowIndex)))
            {
                m_Pl.RemoveFromInternalList(e.RowIndex);
                this.dPlaylist.Rows.Remove(dPlaylist[0, e.RowIndex].OwningRow);
            }

            if (e.RowIndex < m_LastSelectedRow)
                m_LastSelectedRow -= 1;
        }



        private void ExitApp()
        {
            if (m_Handler.AskPlaylistSavingOnClose())
            {
                if (CPlaylistStatus.PlaylistChanged)
                {
                    fMessagebox box = new fMessagebox("Voize information", "Playlist has changed. Save?");

                    if (box.ShowDialog() == DialogResult.OK)
                        this.SavePlaylist();

                }
            }

            Factory fac = new Factory();
            ISaver LocationSaver = fac.Create();

            LocationSaver.SaveSizeAndLocation(this);

            //For making sure that OnFormClose e.Cancel = true does not get triggered here.
            this.WindowState = FormWindowState.Minimized;

            m_Handler.SaveLastSessionPlayList(m_Pl.SoundCollection);

            if (m_Server != null)
                if (m_Server.IsRunning)
                    m_Server.Stop();

            Application.Exit();
        }
        #endregion

        #region Events


        private void bPlaylist_Click(object sender, EventArgs e)
        {
            if (this.splitContainer1.Panel2Collapsed == true)
            {
                this.splitContainer1.Panel2Collapsed = false;
                this.Height = m_List_Height;
            }
            else
            {
                m_List_Height = this.Height;
                this.splitContainer1.Panel2Collapsed = true;
                this.Height = 225;
            }
        }



        private void bPrev_MouseDown(object sender, MouseEventArgs e)
        {
            bPrev.Image =
             Image.FromFile(Application.StartupPath + @"\Icons\player_fwd_green.png");
        }



        private void bPrev_MouseUp(object sender, MouseEventArgs e)
        {
            bPrev.Image =
               Image.FromFile(Application.StartupPath + @"\Icons\player_fwd.png");
        }



        private void bNext_MouseDown(object sender, MouseEventArgs e)
        {
            bNext.Image =
               Image.FromFile(Application.StartupPath + @"\Icons\player_rew_green.png");
        }



        private void bNext_MouseUp(object sender, MouseEventArgs e)
        {
            bNext.Image =
                Image.FromFile(Application.StartupPath + @"\Icons\player_rew.png");
        }



        private void bNext_Click(object sender, EventArgs e)
        {
            this.NextSong();
        }



        private void bPrev_Click(object sender, EventArgs e)
        {
            this.PreviousSong();
        }


        private void dPlaylist_SelectionChanged(object sender, EventArgs e)
        {
            if (CPlayerStatus.WantChangeSong == true)
            {
                if (CPlayerStatus.PlayListLoaded == false)
                {
                    if (this.dPlaylist.SelectedCells[0].Value != null)
                    {
                        string val = (string)this.dPlaylist.SelectedCells[0].Value;
                        if (val.StartsWith("http://") || val.EndsWith(".pls"))
                        {
                            m_Pl.CurrentSongIndex = this.dPlaylist.SelectedCells[0].RowIndex;
                            m_WebStream.Stop();
                            m_Player.Stop();
                            m_Player.ClearPlayPositionIndicatorValue();
                            if (m_WebStream.Play(val,m_Volume))
                            {
                                bPause.Image =
                                   Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
                                this.label1.Text = "00:00";
                                this.label2.Text = " [00:00]";
                                this.PlayBar.Enabled = false;

                                m_ScrollingDisplay.StopScrolling();
                                m_ScrollingDisplay.SetDisplayText = val;
                                m_ScrollingDisplay.StartScrolling();

                                m_LastSelectedRow = this.dPlaylist.SelectedCells[0].RowIndex;
                            }
                        }
                        else
                        {
                            try
                            {
                                //Just in case if a stream is playing
                                m_WebStream.Stop();

                                this.PlayBar.Enabled = true;
                                m_Player.Play(m_Pl.GetSong(this.dPlaylist.SelectedCells[0].RowIndex),
                                    (float)m_Volume.CurrentVolumeLevel / (float)10,Mixer.CurrentPan,
                                     Mixer.CurrentPlayingSpeed,m_Volume);
                      
                                this.label2.Text = " [" + m_Player.GetPlayingTime + "]";

                                bPause.Image =
                                   Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
                                m_ScrollingDisplay.StopScrolling();
                                m_ScrollingDisplay.SetDisplayText = (string)this.dPlaylist.SelectedCells[0].Value;
                                m_ScrollingDisplay.StartScrolling();

                                m_LastSelectedRow = this.dPlaylist.SelectedCells[0].RowIndex;

                               
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                }

                this.HighlightPlayingSong();
            }
        }



        private void bPause_Click(object sender, EventArgs e)
        {
            this.PlayPause();
        }



        private void fPlayer_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3)
                this.ShowSearch();
            if (e.KeyCode == Keys.P || e.KeyCode == Keys.MediaPlayPause)
                this.PlayPause();
            if (e.KeyCode == Keys.S && e.Control)
                this.SavePlaylist();
            if (e.KeyCode == Keys.Z || e.KeyCode == Keys.MediaPreviousTrack)
                this.PreviousSong();
            if (e.KeyCode == Keys.X || e.KeyCode == Keys.MediaNextTrack)
                this.NextSong();
        }


        private void MnuQuit_Click(object sender, EventArgs e)
        {
            this.ExitApp();
        }



        private void MnuSavePls_Click(object sender, EventArgs e)
        {
            this.SavePlaylist();           
        }


        private void MnuImport_Click(object sender, EventArgs e)
        {
			this.Import();
        }


        private void splitContainer1_Panel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                CMenu.Show(splitContainer1.Panel1, new Point(e.X, e.Y));
        }



        private void MnuOpen_Click(object sender, EventArgs e)
        {
			this.Open();
        }


        private void fPlayer_Load(object sender, EventArgs e)
        {
            Factory fac = new Factory();
            ISaver LocationLoader = fac.Create();
            MoveControl WindowMover = new MoveControl(this);

            WindowMover.AllowMoving = true;

            if(m_Handler.RememberWindowSizeAndLocation() == true)
                LocationLoader.GetSizeAndLocation(this);

            if (!m_SkipLastSessionPlaylist)
            {
                if (m_Handler.RememberLastSessionOnStartup() == true)
                {
                    if (File.Exists(m_Handler.GetLastSessionPlaylistName()))
                    {
                        this.Cursor = Cursors.WaitCursor;
                        //m_Pl.Load() "root" not needed with .voize playlists.
                        m_Pl.Load(m_Handler.GetLastSessionPlaylistName(), "");
                        this.Cursor = Cursors.Default;
                    }
                }
            }

            if (m_Settings.IsScrobblingEnabled == "true")
                CScrobblingSupport.Enabled = true;

            if (m_FileFromLoad)
                this.AddFileFromArgument();

            if (m_Settings.IsServerEnabled == "true")
            {
                CRemotePlayer RemotePlayer = new CRemotePlayer(m_Player);
                m_Server = new CServer(Int32.Parse(m_Settings.ServerPort), RemotePlayer);
                m_Server.Start();
            }

            this.CustomScrollbar.Maximum = dPlaylist.Height;
        }



        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams p = base.CreateParams;
                p.ClassStyle |= NativeHook.DROPSHADOW;
                return p;
            }
        }



        private void fPlayer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_Handler.MinimizeToSystemTrayOnClose() == true)
            {              
                    e.Cancel = true;
                    this.WindowState = FormWindowState.Minimized;                
            }
            else
                this.ExitApp();
        }



        private void PlayBar_Scroll(object sender, EventArgs e)
        {
            m_Player.SetPlayPosition((uint)this.PlayBar.Value);
        }




        private void MnuSearch_Click(object sender, EventArgs e)
        {
            this.ShowSearch();
        }



        private void MnuSettings_Click(object sender, EventArgs e)
        {
            fSettings settings = new fSettings(m_Settings);
            settings.ShowDialog();
        }




        private void SysMnuNext_Click(object sender, EventArgs e)
        {
            CPlayerStatus.PlayListLoaded = false;
            m_Pl.NextSong();
            bPause.Image =
                    Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
        }




        private void SysMnuPrevious_Click(object sender, EventArgs e)
        {
            CPlayerStatus.PlayListLoaded = false;
            m_Pl.PreviousSong();
            bPause.Image =
                    Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
        }



        private void SysMenuPause_Click(object sender, EventArgs e)
        {
            this.PlayPause();
        }



        private void SysMnuQuit_Click(object sender, EventArgs e)
        {
            this.ExitApp();
        }



        private void fPlayer_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.ShowInTaskbar = false;

            this.m_Height = this.Height;
            
            if (this.CustomScrollbar.Value > (dPlaylist.Height - 50))
                this.CustomScrollbar.Value = dPlaylist.Height - 80;

           
        }



        private void SysTrayIcon_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }



        private void dPlaylist_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           
            if (e.Button == MouseButtons.Left)
            {
                int selection = dPlaylist.SelectedCells[0].RowIndex;

                CPlayerStatus.WantChangeSong = false;
                if (e.Clicks < 2)
                {
                    dPlaylist[0, e.RowIndex].Selected = false;
                    this.HighlightPlayingSong();
                    dPlaylist[0, e.RowIndex].Style.ForeColor = Color.Gray;
                }
            }

             m_Ev = e; //Save the event
        }


        private void MnuClearPlaylist_Click(object sender, EventArgs e)
        {
			this.ClearList();
        }


        private void SysTrayIcon_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_Pl.CurrentSongNameForPopUp != null)
            {
                //Display mouse hover popup only for normal files. Not for streams because
                //the logic how the names displayed cannot be easily used with streams.
                //TODO: FIX sometimes displays wrong name.
                if (!m_Pl.CurrentSongNameForPopUp.StartsWith("http") || !m_Pl.CurrentSongNameForPopUp.EndsWith(".pls"))
                {
                    string CurrentSongNameForPopUp = m_Pl.CurrentSongNameForPopUp + " " +
                        "[" + m_Player.GetPlayingTime + "]";

                    if (CurrentSongNameForPopUp.Length > 41)
                    {
                        StringBuilder sb = new StringBuilder(CurrentSongNameForPopUp);
                        CurrentSongNameForPopUp = sb.ToString(0, 41);
                        //Limited max 64 chars, 41 + playing time should be less than 64
                    }


                    if (m_Player.IsPaused == false)
                        this.SysTrayIcon.Text = CurrentSongNameForPopUp;

                    else
                        this.SysTrayIcon.Text = CurrentSongNameForPopUp + " (Paused)";
                }
            }

        }



        private void bRnd_Click(object sender, EventArgs e)
        {
			this.SetRandom();
        }



        private void bRnd_MouseHover(object sender, EventArgs e)
        {
            
            m_Tip.Show("Random play", bRnd);
        }



        private void PlayBar_ValueChanged(object sender, EventArgs e)
        {
            string pos;
            string min;
            string sec;

            min = TimeSpan.FromMilliseconds(this.PlayBar.Value).Minutes.ToString();
            sec = TimeSpan.FromMilliseconds(this.PlayBar.Value).Seconds.ToString();

            if (min.Length == 1)
                min = "0" + min;

            if (sec.Length == 1)
                sec = "0" + sec;

            pos = min + ":" + sec;

            this.label1.Text = pos;

            Application.DoEvents();
        }



        private void MnuIdtags_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            fId3 id3 = new fId3(m_Pl.SoundCollection);
            if (id3.ShowDialog() == DialogResult.OK)
            {               
                //Prevent playlist selection change
                CPlayerStatus.PlayListLoaded = true;
                m_Pl.Reload();
              
            }
            this.Cursor = Cursors.Default;
        }



        private void tFileDisplay_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show(this.tFileDisplay.Text,this.tFileDisplay);
        }


		private void pDisplay_MouseClick(object sender, MouseEventArgs e)
		{
			this.StartStopScrolling();
		}



		private void tFileDisplay_MouseClick(object sender, MouseEventArgs e)
		{
			this.StartStopScrolling();
		}



		private void MnuAbout_Click(object sender, EventArgs e)
		{
			fAbout AboutDialog = new fAbout();
			AboutDialog.ShowDialog();
		}



		private void SysTrayMenu_Popup(object sender, EventArgs e)
		{
			if (m_Player.IsPaused)
				SysMenuPause.Text = "Play";
			else
				SysMenuPause.Text = "Pause";
		}



		private void SysMnuRandom_Click(object sender, EventArgs e)
		{
			this.SetRandom();
		}



		private void MnuUrl_Click(object sender, EventArgs e)
		{
			
			fUrl UrlDialog = new fUrl();
			if (UrlDialog.ShowDialog() == DialogResult.OK)
			{
				m_WebStream.SetUrl(UrlDialog.Url);
				m_ScrollingDisplay.StopScrolling();
				m_ScrollingDisplay.SetDisplayText = m_WebStream.DisplayString;
				m_ScrollingDisplay.StartScrolling();
				m_Pl.AddUrl(m_WebStream.Url);

				bPause.Image =
					   Image.FromFile(Application.StartupPath + @"\Icons\player_pause.png");
			}
		}



        private void dPlaylist_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                CPlayerStatus.PlayListLoaded = false;
                CPlayerStatus.WantChangeSong = true;
                this.dPlaylist.SelectedCells[0].Selected = true;
                CPlayerStatus.WantChangeSong = false;
            }
        }



        private void bPlay_Click(object sender, EventArgs e)
        {
            if (dPlaylist.RowCount >= 1)
            {
                CPlayerStatus.PlayListLoaded = false;
                CPlayerStatus.WantChangeSong = true;
                bool notfound = false;
               
                for (int i = 0; i < dPlaylist.RowCount - 1; i++)
                {
                    if (dPlaylist[0, i].Style.ForeColor == Color.Gray)
                        dPlaylist[0, i].Selected = true;
                  
                    notfound = true; //Cannot find selection
                }

                if (notfound)
                {
                    for (int i = 0; i < dPlaylist.RowCount - 1; i++)
                    {
                        if (dPlaylist[0, i].Style.ForeColor == Color.White)
                            dPlaylist[0, i].Selected = true;
                    }
                }

                CPlayerStatus.WantChangeSong = false;

                if (m_Player.IsPaused)
                    this.PlayPause();
           }
        }



        private void bPlay_MouseDown(object sender, MouseEventArgs e)
        {
            bPlay.Image =
                       Image.FromFile(Application.StartupPath + @"\Icons\player_play_green.png");
        }



        private void bPlay_MouseUp(object sender, MouseEventArgs e)
        {
            bPlay.Image =
                      Image.FromFile(Application.StartupPath + @"\Icons\player_play.png");
        }



        private void mnuRemove_Click(object sender, EventArgs e)
        {
            this.RemoveSongFromPlaylist(m_Ev);
        }



        private void dPlaylist_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                this.HighlightPlayingSong();

                DataGridView.HitTestInfo hitTestInfo;
                hitTestInfo = dPlaylist.HitTest(e.X, e.Y);
                // If column is first column. At the moment it will always be.
                if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 0)
                {
                    m_LastPopupIndex = hitTestInfo.RowIndex;
                    m_LastPopupColor = dPlaylist[0, hitTestInfo.RowIndex].Style.ForeColor;
                    dPlaylist[0, hitTestInfo.RowIndex].Style.ForeColor = Color.DarkGray;
                    MenuSingleSong.Show(dPlaylist, new Point(e.X, e.Y)); 
                }
                
            }
        }



        private void bImport_Click(object sender, EventArgs e)
        {
            this.Import();
        }

    
        private void bAdd_Click(object sender, EventArgs e)
        {
            this.Open();
        }



        private void bMenu_MouseClick(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Left && e.Clicks == 1)
                CMenu.Show(bMenu, new Point(e.X,e.Y), LeftRightAlignment.Left);
        }



        private void bVolume_Click(object sender, EventArgs e)
        {
            //TODO: Check what happens when webstream is muted and normal file starts playing.
            if (m_WebStream.IsPlaying)
            {
                m_WebStream.Mute();

                if(m_WebStream.IsMuted)
                    this.bVolume.Image =
                           Image.FromFile(Application.StartupPath + @"\Icons\volume_muted.png");
                else
                    this.bVolume.Image =
                           Image.FromFile(Application.StartupPath + @"\Icons\volume.png");
            }
            else
            {
                if (m_Volume.SoundHandler != null)
                {
                    if (m_Volume.IsMuted == false)
                    {
                        m_Volume.Mute();
                        this.VolumeControlHost.Enabled = false;
                        this.bVolume.Image =
                            Image.FromFile(Application.StartupPath + @"\Icons\volume_muted.png");
                    }
                    else
                    {
                        this.VolumeControlHost.Enabled = true;
                        m_Volume.SetVolumeLevel(m_Volume.CurrentVolumeLevel);
                        this.bVolume.Image =
                           Image.FromFile(Application.StartupPath + @"\Icons\volume.png");
                    }
                }
            }
        }



        private void bMixer_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show("Mixer", bMixer);
        }



        private void bAdd_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show("Add file or open a playlist", bAdd);
        }



        private void bImport_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show("Import folder", bImport);
        }



        private void bMenu_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show("Show menu", bMenu);
        }



        private void bVolume_MouseHover(object sender, EventArgs e)
        {
            m_Tip.Show("Mute/Unmute volume", bVolume);
        }



        private void bMixer_Click(object sender, EventArgs e)
        {           
            if (m_IsMixerShown)
            {
                m_Mixer.Close();
                m_IsMixerShown = false;
                bMixer.Text = " E";
            }
            else
            {
                m_Mixer = new fMixer();
                m_Mixer.Location = new Point(Cursor.Position.X - m_Mixer.Width / 2, 
                    Cursor.Position.Y - (m_Mixer.Height + 20));
                m_Mixer.SetConnection(m_Player.Sound);
                m_Mixer.Show();
                m_IsMixerShown = true;
                bMixer.Text = " X";
            }
        }



        private void bClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void bMinimizeWindow_Click_1(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
                this.WindowState = FormWindowState.Minimized;
            else
                this.WindowState = FormWindowState.Normal;
        }



        private void bClose_MouseDown(object sender, MouseEventArgs e)
        {
            this.bClose.Image = Image.FromFile(Application.StartupPath + @"\Icons\close_down.png");
        }



        private void bClose_MouseUp(object sender, MouseEventArgs e)
        {
            this.bClose.Image = Image.FromFile(Application.StartupPath + @"\Icons\button.close.png");
        }



        private void bMinimizeWindow_MouseDown(object sender, MouseEventArgs e)
        {
            this.bMinimizeWindow.Image = Image.FromFile(Application.StartupPath + @"\Icons\min_down.png");
        }




        private void bMinimizeWindow_MouseUp(object sender, MouseEventArgs e)
        {
            this.bMinimizeWindow.Image = Image.FromFile(Application.StartupPath + @"\Icons\button.min.png");
        }




        private void bClose_MouseHover(object sender, EventArgs e)
        {
            this.bClose.Image = Image.FromFile(Application.StartupPath + @"\Icons\close_hover.png");
        }




        private void bClose_MouseLeave(object sender, EventArgs e)
        {
            this.bClose.Image = Image.FromFile(Application.StartupPath + @"\Icons\button.close.png");
        }



        private void bMinimizeWindow_MouseHover(object sender, EventArgs e)
        {
            this.bMinimizeWindow.Image = Image.FromFile(Application.StartupPath + @"\Icons\min_hover.png");
        }




        private void bMinimizeWindow_MouseLeave(object sender, EventArgs e)
        {
            this.bMinimizeWindow.Image = Image.FromFile(Application.StartupPath + @"\Icons\button.min.png");
        }




        private void bPlaylist_MouseDown(object sender, MouseEventArgs e)
        {
            this.bPlaylist.Image = Image.FromFile(Application.StartupPath + @"\Icons\playlist_green.png");
        }



        private void bPlaylist_MouseUp(object sender, MouseEventArgs e)
        {
            this.bPlaylist.Image = Image.FromFile(Application.StartupPath + @"\Icons\playlist.png");
        }



        private void CustomScrollbar_Scroll(object sender, EventArgs e)
        {
           //TODO: Make this less hacky           
            try
            {
                dPlaylist.FirstDisplayedScrollingRowIndex = CustomScrollbar.Value;
            }
            catch (ArgumentOutOfRangeException ae)
            {

            }

            this.CustomScrollbar.Maximum = dPlaylist.Height;
        }



        private void dPlaylist_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            CustomScrollbar.Maximum = dPlaylist.RowCount;
        }



        private void dPlaylist_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            CustomScrollbar.Maximum = dPlaylist.RowCount;
        }



        private void fPlayer_Shown(object sender, EventArgs e)
        {
            this.CustomScrollbar.Value = 0;
        }



        private void fPlayer_ResizeEnd(object sender, EventArgs e)
        {
            this.CustomScrollbar.Maximum = dPlaylist.Height;
        }

        #endregion

    }

        
}

